package td.ejb.users;

import java.io.Serializable;
import java.util.List;

import javax.persistence.*;

import org.apache.commons.codec.digest.DigestUtils;

import td.ejb.users.UserDTO;

@Entity
@Table(name = "USERS")
@NamedQueries({ @NamedQuery(name = User.FIND_BY_GROUP, query = "SELECT u FROM User u WHERE u.gruppo=:gruppo"), 
				@NamedQuery(name = User.FIND_BY_USERNAME, query = "SELECT u FROM User u WHERE u.username=:username"), 
				@NamedQuery(name = User.FIND_BY_EMAIL, query = "SELECT u FROM User u WHERE u.email=:email") })
public class User implements Serializable {
	private static final long serialVersionUID = 1L;
	public static final String FIND_BY_GROUP = "User.findAllAgent";
	public static final String FIND_BY_USERNAME = "User.findByUsername";
	public static final String FIND_BY_EMAIL = "User.findByEmail";

	@Id
	private String username;
	private String password;
	private String nome;
	private String cognome;
	
	@Column(unique = true, nullable = false)
	private String email;

	@Enumerated(EnumType.STRING)
	private Group gruppo;

	@ElementCollection(targetClass = Group.class)
	@CollectionTable(name = "USERS_GROUPS", joinColumns = @JoinColumn(name = "username"))
	@Enumerated(EnumType.STRING)
	@Column(name = "groupname")
	private List<Group> groups;

	public User() {
		super();
	}

	public User(UserDTO user, Boolean pswCript) {
		this.username = user.getUsername();
		this.nome = user.getNome();
		this.cognome = user.getCognome();
		this.email = user.getEmail();
		this.gruppo = Group.valueOf(user.getGruppo());
		if (pswCript) {
			this.password = user.getPassword();
		} else {
			this.password = DigestUtils.sha256Hex(user.getPassword());
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public String getCognome() {
		return cognome;
	}

	public void setCognome(String cognome) {
		this.cognome = cognome;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Group getGruppo() {
		return gruppo;
	}

	public void setGruppo(Group gruppo) {
		this.gruppo = gruppo;
	}

	public List<Group> getGroups() {
		return groups;
	}

	public void setGroups(List<Group> groups) {
		this.groups = groups;
	}

	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", nome=" + nome + ", cognome=" + cognome + ", email=" + email + ", gruppo=" + gruppo + "]";
	}
}
